#ifndef _XPT2046_H_
#define _XPT2046_H_

#include "stm32f10x_rcc.h"
#include "stm32f10x_gpio.h"

#define XPT2046_PENIRQ_GPIO_CLK     RCC_APB2Periph_GPIOF
#define XPT2046_PENIRQ_GPIO_PORT    GPIOF  
#define XPT2046_PENIRQ_GPIO_PIN     GPIO_Pin_9

#define XPT2046_PENIRQ_ActiveLevel  0
#define XPT2046_PENIRQ_Read()       GPIO_ReadInputDataBit(XPT2046_PENIRQ_GPIO_PORT, XPT2046_PENIRQ_GPIO_PIN)

#define XPT2046_SPI_GPIO_CLK        RCC_APB2Periph_GPIOG | RCC_APB2Periph_GPIOF

#define XPT2046_SPI_CLK_PIN         GPIO_Pin_7
#define XPT2046_SPI_CLK_PORT        GPIOG

#define XPT2046_SPI_CS_PIN          GPIO_Pin_10
#define XPT2046_SPI_CS_PORT         GPIOF

#define XPT2046_SPI_MOSI_PIN        GPIO_Pin_11
#define XPT2046_SPI_MOSI_PORT       GPIOF

#define XPT2046_SPI_MISO_PIN        GPIO_Pin_6
#define XPT2046_SPI_MISO_PORT       GPIOF

#define XPT2046_CS_ENABLE()         GPIO_SetBits(XPT2046_SPI_CS_PORT, XPT2046_SPI_CS_PIN)
#define XPT2046_CS_DISABLE()        GPIO_ResetBits(XPT2046_SPI_CS_PORT, XPT2046_SPI_CS_PIN)

#define XPT2046_CLK_HIGH()          GPIO_SetBits(XPT2046_SPI_CLK_PORT, XPT2046_SPI_CLK_PIN)
#define XPT2046_CLK_LOW()           GPIO_ResetBits(XPT2046_SPI_CLK_PORT, XPT2046_SPI_CLK_PIN)

#define XPT2046_MOSI_1()            GPIO_SetBits(XPT2046_SPI_MOSI_PORT, XPT2046_SPI_MOSI_PIN)
#define XPT2046_MOSI_0()            GPIO_ResetBits(XPT2046_SPI_MOSI_PORT, XPT2046_SPI_MOSI_PIN)

#define XPT2046_MISO()              GPIO_ReadInputDataBit(XPT2046_SPI_MISO_PORT, XPT2046_SPI_MISO_PIN)

#define XPT2046_CHANNEL_X           0X90
#define XPT2046_CHANNEL_Y           0XD0




typedef struct         //校准因子结构体 
{
	 float An,  		 //注:sizeof(long double) = 8
					Bn,     
					Cn,   
					Dn,    
					En,    
					Fn,     
					Divider;
	
} strType_XPT2046_Calibration;

// 液晶坐标结构体
typedef struct{
    /* 负值表示无新数据 */             
    int16_t x;          // 记录最新的触摸参数值
    int16_t y;

    /* 用于记录连续触摸时（长按）的上一次触摸位置 */
    int16_t pre_x;
    int16_t pre_y;
}strType_XPT2046_Coordinate;

/* 校准系数结构体 */
typedef struct{
    float dx_x, dx_y, dx, dy_x, dy_y, dy;
}strType_XPT2046_TouchPara;

typedef enum{
    XPT2046_STATE_RELEASE = 0,
    XPT2046_STATE_WAITING,
    XPT2046_STATE_PRESSED,
}enumTouchState;


extern strType_XPT2046_TouchPara strXPT2046_TouchPara[];

#define TOUCH_PRESSED       1
#define TOUCH_NOT_PRESSED   0

/* 触摸消抖阀值 */
#define DURIATION_TIME      2


void xpt2046_Init(void);
uint8_t XPT2046_TouchDetect(void);
uint8_t XPT2046_Get_TouchedPoint_XY(strType_XPT2046_Coordinate * pDisplayCoordinate);
uint8_t xpt2046_ReadADC_Smooth_XY(strType_XPT2046_Coordinate *pScreenCoordinate);

#endif // _XPT2046_

